<template>
  <div class="list-wrapper-class">
    <el-form :inline="true">
      <el-form-item label="绩效时间：">
        <el-date-picker style="width: 150px;" clearable v-model="searchMonth" type="month" :editable="false" placeholder="选择月" @change="kpiMonthChange" value-format="yyyy-MM"></el-date-picker>
      </el-form-item>
      <el-form-item label="选择人员：">
        <el-tooltip class="item" effect="dark" :disabled="pickedUsersName.length === 0" :content="pickedUsersName" placement="bottom">
          <el-input style="width: 150px;" @click="selectDingUsers" placeholder="请选择人员" v-model="pickedUsersName" :disabled="true"></el-input>
        </el-tooltip>
      </el-form-item>
      <el-button @click="selectDingUsers" style="margin-right:15px;">选择</el-button>
      <el-form-item label="考评状态：">
        <el-select style="width: 150px;" v-model="searchStatus" placeholder="请选择">
          <el-option
            v-for="item in kpiStatus"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchList(true)" :loading="dataListLoading">查询</el-button>
        <el-button @click="resetSearch()">重置</el-button>
        <el-button v-if="isPersManager" type="primary" @click="notifyAction()" :loading="notifyLoading">一键通知</el-button>
        <el-button v-if="isPersManager" type="primary" @click="exportExcel()" :loading="notifyLoading">导出</el-button>
        <el-button v-if="isPersManager" type="primary" @click="exportDetail()" :loading="notifyLoading">导出明细</el-button>
        <el-button type="primary" @click="selectEmployee()">设置参与员工</el-button>
      </el-form-item>
    </el-form>
    <div>
      <el-table :height="tableHeight" :data="searchResult" border style="width: 100%" @sort-change="sortList">
        <el-table-column label="序号" type="index" width="100" align="center"></el-table-column>
        <el-table-column label="姓名" prop="dingName" min-width="130" align="center"></el-table-column>
        <el-table-column label="考核月份" prop="kpiDate" width="100" align="center"></el-table-column>
        <el-table-column label="所属部门" prop="department" min-width="180" align="center"></el-table-column>
        <el-table-column label="当前职位" prop="position" min-width="180" align="center"></el-table-column>
        <el-table-column sortable="custom" label="绩效得分" prop="kpiScores" min-width="180" align="center"></el-table-column>
        <el-table-column label="绩效等级" prop="kpiLevel" min-width="180" align="center"></el-table-column>
        <el-table-column label="绩效系数" prop="kpiRatio" min-width="180" align="center"></el-table-column>
        <el-table-column
            label="绩效内容"
            align="center"
            min-width="180">
            <template slot-scope="scope">
              <el-button v-if="isPersManager && scope.row.status <2" @click="openPaperDialog(scope.row)" type="text" size="small">设置{{scope.row.status === 1? '(已设置)': ''}}</el-button>
              <el-button @click="openCheckDialog(scope.row.id, scope.row.dingId)" type="text" size="small">查看</el-button>
            </template>
          </el-table-column>
      </el-table>
    </div>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="page"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <el-dialog title="绩效题目设置" :fullscreen="true" :visible.sync="kpiPaperDialog" :close-on-click-modal="false">
      <el-table :span-method="objectSpanMethod" :data="paperData" border style="width: 100%">
        <el-table-column label="序号" prop="kpiItemPid" width="100" align="center"> </el-table-column>
        <el-table-column label="考核类型" prop="kpiItemType" min-width="110" align="center"> </el-table-column>
        <el-table-column label="分值占比(100%)" width="130" align="center">
          <template slot-scope="scope">
<!--            <div v-if="isMpbUser(currentDingId)">
              <span v-if="scope.row.kpiItemPid === '1'">15%</span>
              <span v-if="scope.row.kpiItemPid === '2'">75%</span>
              <span v-if="scope.row.kpiItemPid === '3'">0%</span>
              <span v-if="scope.row.kpiItemPid === '4'">10%</span>
            </div>-->
            <div>
              <span v-if="scope.row.kpiItemPid === '1'">{{bigItemList[0].scoresPower * 5}}%</span>
              <span v-if="scope.row.kpiItemPid === '2'">{{bigItemList[1].scoresPower * 5}}%</span>
              <span v-if="scope.row.kpiItemPid === '3'">{{bigItemList[2].scoresPower * 5}}%</span>
              <span v-if="scope.row.kpiItemPid === '4'">{{bigItemList[3].scoresPower * 5}}%</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="考核内容" min-width="180" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.kpiItemId" filterable placeholder="请选择" @change="setPoint(scope.row)">
              <el-option v-for="item in itemPidArr[scope.row.kpiItemPid]" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="考核关键点" prop="kpiItemKey" min-width="180" align="left" header-align="center">
          <template slot-scope="scope">
            <div style="white-space: pre-line;">{{scope.row.kpiItemKey}}</div>
          </template>
        </el-table-column>
        <el-table-column label="考核参考指标" prop="kpiItemIndex" min-width="180" align="left" header-align="center">
          <template slot-scope="scope">
            <div style="white-space: pre-line;">{{scope.row.kpiItemIndex}}</div>
          </template>
        </el-table-column>
        <el-table-column label="分值倍数" align="center" width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.scoresPower"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="评分人" align="center" min-width="120">
          <template slot-scope="scope">
            <i v-if="scope.row.scoresGiverIds.length === 0" @click="addAssessor(scope.row)" class="el-icon-circle-plus" style="cursor:pointer;"></i>
            <span v-if="scope.row.scoresGiverIds.length !== 0" @click="addAssessor(scope.row)" style="color:#66b1ff;cursor:pointer;">{{scope.row.scoresGiverNames.join(',')}}</span>
            <i v-if="scope.row.scoresGiverIds.length !== 0" title="设置相同评分人" class="el-icon-s-order"  style="cursor:pointer;" @click="setSameGiver(scope.$index)"></i>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="100">
          <template slot-scope="scope">
            <i v-if="addClassIndex.includes(scope.$index)" @click="addItem(scope)" class="el-icon-circle-plus" style="cursor:pointer;"></i>
            <i @click="removeItem(scope)" class="el-icon-remove" style="cursor:pointer;"></i>
          </template>
        </el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="fetchOrigin()">选择试卷来源</el-button>
        <el-button @click="kpiPaperDialog = false">取 消</el-button>
        <el-button type="primary" @click="savePaper">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="查看绩效成绩" :fullscreen="true" :visible.sync="checkKpiDialog">
      <div>
        <div class="assessed-info">
          <p>所在部门: <span>{{paperUserInfo.department}}</span></p>
          <p>考核岗位: <span>{{paperUserInfo.position}}</span></p>
          <p>被考核人: <span>{{paperUserInfo.dingName}}</span></p>
          <p>考核月份: <span>{{paperUserInfo.kpiDate}}</span></p>
        </div>
      </div>
      <div style="margin-top:20px;">
        <el-table :span-method="objectSpanMethod" :data="checkKpiData" border style="width: 100%" :summary-method="getSummaries" show-summary>
          <el-table-column label="序号" prop="kpiItemPid" width="100" align="center"></el-table-column>
          <el-table-column label="考核类型" prop="kpiItemType" min-width="120" align="center"></el-table-column>
          <el-table-column label="分值占比(100%)" width="130" align="center">
            <template slot-scope="scope">
<!--              <div v-if="isMpbUser(currentDingId)">
                <span v-if="scope.row.kpiItemPid === '1'">15%</span>
                <span v-if="scope.row.kpiItemPid === '2'">75%</span>
                <span v-if="scope.row.kpiItemPid === '3'">0%</span>
                <span v-if="scope.row.kpiItemPid === '4'">10%</span>
              </div>-->
              <div>
                <span v-if="scope.row.kpiItemPid === '1'">{{bigItemList[0].scoresPower * 5}}%</span>
                <span v-if="scope.row.kpiItemPid === '2'">{{bigItemList[1].scoresPower * 5}}%</span>
                <span v-if="scope.row.kpiItemPid === '3'">{{bigItemList[2].scoresPower * 5}}%</span>
                <span v-if="scope.row.kpiItemPid === '4'">{{bigItemList[3].scoresPower * 5}}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="考核内容" prop="kpiItemName" min-width="220" align="left" header-align="center"></el-table-column>
          <el-table-column label="考核关键点" prop="kpiItemKey" min-width="220" align="left" header-align="center">
            <template slot-scope="scope">
              <div style="white-space: pre-line;">{{scope.row.kpiItemKey}}</div>
            </template>
          </el-table-column>
          <el-table-column label="考核参考指标" prop="kpiItemIndex" min-width="220" align="left" header-align="center">
            <template slot-scope="scope">
              <div style="white-space: pre-line;">{{scope.row.kpiItemIndex}}</div>
            </template>
          </el-table-column>
          <el-table-column label="分值倍数" prop="scoresPower" width="100" align="center"></el-table-column>
          <el-table-column label="绩效分值" prop="scores" width="100" align="center">
            <template slot-scope="scope">
              <del v-if="scope.row.oldScores !== ''">{{scope.row.oldScores}}</del>
              <span>{{scope.row.scores}}</span>
              <span v-if="isPersManager && scope.row.scores !== '' && scope.row.status === 3" style="color:#66b1ff;cursor:pointer;" @click="openReAssessDialog(scope.row)"><i class="el-icon-edit-outline"></i></span>
              <el-tooltip v-if="scope.row.oldScores !== ''" placement="bottom" effect="light">
                <div slot="content">
                  {{scope.row.remark}}
                </div>
                <span style="color:#66b1ff;cursor:pointer;"><i class="el-icon-tickets"></i></span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column v-if="isPersManager" label="评分详情" width="150" align="center">
            <template slot-scope="scope">
              <p v-for="item in scope.row.scoresGivers" :key="item.id">
                {{item.scoresGiverName}}({{item.scores !== '' ? item.scores + '分' : '未评分'}})
                <el-tooltip placement="bottom" effect="light">
                  <div slot="content">
                    {{item.remark}}
                  </div>
                  <span style="color:#66b1ff;cursor:pointer;"><i class="el-icon-tickets"></i></span>
                </el-tooltip>
              </p>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="width:100%;height:20px;"></div>
    </el-dialog>
    <el-dialog title="评分窗口" :visible.sync="reAssessDialog" width="600px">
      <el-form :model="scoreForm" style="padding-right:100px;">
        <el-form-item label="分数：" :label-width="formLabelWidth">
          <el-rate v-model="scoreForm.scores" style="margin-top:8px;"></el-rate>
          <span style="position:absolute;top:0;right:0;cursor:pointer;color:#66b1ff;" @click="scoreForm.scores = 0;">分数清零</span>
        </el-form-item>
        <el-form-item label="评分依据：" :label-width="formLabelWidth">
          <el-input type="textarea" :rows="5" placeholder="请输入评分的依据" v-model="scoreForm.remark"></el-input>
        </el-form-item>
        <p class="notice">注：要求评分公正、公平、严谨，评分范围0-5星。如发现有徇私舞弊现象，将追究评分人和被评分人的责任。</p>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reAssessDialog = false">取 消</el-button>
        <el-button type="primary" @click="reAssess">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import dingMixin from  '@/mixins/ding'
  import {dateUtil} from '@/utils/dateUtil'
  import formUtil from '@/utils/formUtil'
  import * as dd from 'dingtalk-jsapi'
  export default {
    data () {
      return {
        departments: [],
        searchDep:'',
        value: '',
        reAssessDialog: false,
        pickedUsersName:'',
        dataListLoading: false,
        kpiRatioDialog: false,
        checkKpiDialog: false,
        mpbRoleId: '1265176800377499649',
        mpbUsers: [],
        pickedUsers: [],
        scoreForm: {
          scores: 1,
          remark: '',
          paperDetailId: ''
        },
        kpiStatus: [{
          value: '-1',
          label: '全部'
        }, {
          value: '1',
          label: '已完成'
        }, {
          value: '0',
          label: '未完成'
        }, {
          value: '11',
          label: '已设置'
        }, {
          value: '10',
          label: '未设置'
        }],
        searchStatus: '-1',
        kpiPaperDialog: false,
        form: {
          score: 0,
          desc: ''
        },
        formLabelWidth: '120px',
        searchResult: [],
        paperData: [],
        OrderIndexArr: [],
        OrderIndexLenth: [],
        addClassIndex : [],
        searchMonth:'',
        currentDingId: '',
        currentPaperId: '',
        currentPaperDept: '',
        itemPidArr:{
          1:[],
          2:[],
          3:[],
          4:[]
        },
        checkKpiData: [],
        paperUserInfo:{},
        itemTemplate:{
          1: {
            kpiItemPid:'1',
            kpiItemId:'',
            scoresPower:'',
            scoresGiverIds: [],
            scoresGiverNames: [],
            kpiItemType:'本职常规职责',
            kpiItemKey:'',
            kpiItemIndex:''
          },
          2: {
            type:2,
            kpiItemPid:'2',
            kpiItemId:'',
            scoresPower:'',
            scoresGiverIds: [],
            scoresGiverNames: [],
            kpiItemType:'岗位核心价值',
            kpiItemKey:'',
            kpiItemIndex:''
          },
          3: {
            kpiItemPid:'3',
            kpiItemId:'',
            scoresPower:'',
            scoresGiverIds: [],
            scoresGiverNames: [],
            kpiItemType:'业务规范要求',
            kpiItemKey:'',
            kpiItemIndex:''
          },
          4: {
            kpiItemPid:'4',
            kpiItemId:'',
            scoresPower:'',
            scoresGiverIds: [],
            scoresGiverNames: [],
            kpiItemType:'价值观与品格',
            kpiItemKey:'',
            kpiItemIndex:''
          },
        },
        bigItemList: [{scoresPower: 0}, {scoresPower: 0}, {scoresPower: 0}, {scoresPower: 0}],
        notifyLoading: false,
        pageSize: 10,
        page:1,
        totalPage: 0,
        scoresAsc: '',
        kpiItemPidArr: ['1','2','3','4'],
        tableHeight: window.tableHeight
      }
    },
    activated() {
      this.tableHeight = document.documentElement['clientHeight'] - 270
      window.onresize = () => {
        this.tableHeight = document.documentElement['clientHeight'] - 270
      }
    },
    computed: {
      isDeptManager() {
        return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1239352423883046914')
      },
      isPersManager() {
        return this.userInfo.roleIdList && this.userInfo.roleIdList.includes('1239351906259795970')
      }
    },
    mixins: [dingMixin, dateUtil],
    created() {
      if (dd.env.platform!="notInDingTalk") {
        this.run_dd_config();
        if(this.userInfo && this.userInfo.dingId && this.dingConfig.corpId && this.$cookie.get('token')>'') {
          return;
        }
        this.getDingConfig().then(config =>{
          this.dingConfig = config;
          this.dingLogin(config.corpId, null);
        })
      }
    },
    mounted(){
      this.searchMonth = dateUtil.thisMonth();
      this.$http({
        url: this.$http.adornUrl('/sys/dept/list'),
        method: 'get'
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.departments = data.data;
        }else {
          this.$message.error(data.msg)
        }
      })
      this.searchList();
      this.getScoreRange();
      this.getKpiEmployee();
      this.getMpbRoleUsers();
    },
    methods: {
      selectEmployee(){
        this.complexPicker(300, [], this.employeeIds).then((data)=>{
          this.employeeIds = data.map(item => item.emplId);
          this.$http({
            url: this.$http.adornUrl('/kpi/paper/setKpiEmployees'),
            method: 'post',
            params: this.$http.adornParams({
              dingIds: this.employeeIds.join(','),
              kpiDate: this.searchMonth
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
            }else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      getKpiEmployee(){
        this.$http({
          url: this.$http.adornUrl('/kpi/paper/getKpiEmployees'),
          method: 'get',
          params: this.$http.adornParams({
            kpiDate: this.searchMonth
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.employeeIds = data.data;
          }
        })
      },
      async getMpbRoleUsers() {
        this.mpbUsers = await this.$httpN.postQ('sys/user/listUserByRoleId', {roleId: this.mpbRoleId});
      },
      isMpbUser(dingId){
/*        for(let m of this.mpbUsers){
          if(m.emplId===dingId){
            return true
          }
        }*/
        return false
      },
      kpiMonthChange(){
        this.getKpiEmployee();
      },
      resetSearch() {
        //this.searchMonth = dateUtil.thisMonth();
        this.pickedUsersName = '';
        this.pickedUsers = [];
        this.searchStatus = '-1'
      },
      getScoreRange() {
        this.$http({
          url: this.$http.adornUrl('/kpi/item/listBigItem'),
          method: 'get'
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.bigItemList = data.data;
          }
        })
      },
      sortList(sort) {
        this.scoresAsc = sort.order === 'ascending'? true: sort.order === 'descending'? false : '';
        this.searchList(true);
      },
      selectDingUsers(){
        this.complexPicker(300, this.isPersManager ? []: this.unPermDingIds.split(','), this.pickedUsers).then((data)=>{
          this.pickedUsers = [];
          let names = '';
          data.forEach((item, idx) => {
            names+= item.name;
            this.pickedUsers.push(item.emplId)
            if(idx !== (data.length - 1)) names += ','
          })
          this.pickedUsersName = names;
        })
      },
      fetchOrigin() {
        this.complexPicker(1).then((data)=>{
          this.$http({
            url: this.$http.adornUrl('/kpi/paper/list'),
            method: 'post',
            data: this.$http.adornParams({
              'kpiDate': this.searchMonth,
              'paperStatus': '-1',
              'dingId': data[0].emplId,
              'page': 1,
              'limit': 1,
              'scoresAsc': ''
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              let paperId = data.data.list[0].id;
              this.getPaperDetail({id: paperId}, true)
            }else {
              this.$message.error(data.msg)
            }
          })
        })
      },
      setSameGiver(idx) {
        this.paperData[idx+1].scoresGiverIds = [...this.paperData[idx].scoresGiverIds];
        this.paperData[idx+1].scoresGiverNames = [...this.paperData[idx].scoresGiverNames];
      },
      addAssessor(currentRow) {
        this.complexPicker(5, [], currentRow.scoresGiverIds).then((data)=>{
          currentRow.scoresGiverIds = [];
          currentRow.scoresGiverNames = [];
          data.forEach((item, idx) => {
            currentRow.scoresGiverIds.push(item.emplId)
            currentRow.scoresGiverNames.push(item.name)
          })
        })
      },
      computedColLine(target) {
        this.OrderIndexLenth = [];
        this.OrderIndexArr = [0];
        this.kpiItemPidArr.forEach((item) => {
          let count = 0;
          target.forEach((data) => {
            if(data.kpiItemPid === item) count++
          })
          if(count !== 0) {
            this.OrderIndexLenth.push(count)
            this.OrderIndexArr.push(this.OrderIndexArr[this.OrderIndexArr.length -1] + count)
          }
        })
      },
      getSummaries(param) {
        const { columns, data } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            return sums[index] = '绩效等级';
          }else if(index === 1) {
            return sums[index] = this.paperUserInfo.kpiLevel;
          }else if(index === 2) {
            return sums[index] = '绩效系数';
          }else if(index === 3){
            return sums[index] = this.paperUserInfo.kpiRatio;
          }else if(index === 6){
            return sums[index] = '总分';
          }else if(index === 7) {
            return sums[index] = this.paperUserInfo.kpiScores;
          }else {
            sums[index] = '';
          }
        });

        return sums;
      },
      openCheckDialog(id, dingId) {
        this.checkKpiDialog = true;
        this.currentPaperId = id;
        this.currentDingId = dingId;
        this.$http({
          url: this.$http.adornUrl('/kpi/paper/withDetailById'),
          method: 'post',
          params: this.$http.adornParams({
            'paperId': id,
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.paperUserInfo = data.data.paper;
            this.checkKpiData = data.data.items;
            this.checkKpiData.forEach((item) => {
              item.status = this.paperUserInfo.status
            })
            this.computedColLine(this.checkKpiData);
          }else {
            this.$message.error(data.msg)
          }
        })
      },
      sizeChangeHandle(limit) {
        this.pageSize = limit;
        this.searchList(true);
      },
      currentChangeHandle(page) {
        this.page = page;
        this.searchList();
      },
      searchList(init) {
        if(init) this.page = 1;
        this.searchLoading = true;
        this.$http({
          url: this.$http.adornUrl('/kpi/paper/list'),
          method: 'post',
          data: this.$http.adornParams({
            'kpiDate': this.searchMonth,
            'paperStatus': this.searchStatus,
            'dingId': this.pickedUsers.join(','),
            'page': this.page,
            'limit': this.pageSize,
            'scoresAsc': this.scoresAsc
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.searchResult = data.data.list;
            this.totalPage = data.data.totalCount
          }else {
            this.$message.error(data.msg)
          }
        }).finally(() => {
          this.searchLoading = false;
        })
      },
      setPoint(row) {
        this.itemPidArr[row.kpiItemPid].forEach((item) => {
          if(item.id === row.kpiItemId) {
            row.kpiItemKey = item.keyPoint;
            row.kpiItemIndex = item.indexPoint;
            row.scoresPower = item.scoresPower;
          }
        })
      },
      objectSpanMethod({ row, column, rowIndex, columnIndex }) {
        if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
          let result;
          let index = this.OrderIndexArr.indexOf(rowIndex);
          return result = {
              rowspan: index < 0? 0: this.OrderIndexLenth[index],
              colspan: index < 0? 0: 1
          }
        }
      },
      openPaperDialog(target) {
        this.itemPidArr = {
          1:[],
          2:[],
          3:[],
          4:[]
        }
        this.currentDingId = target.dingId;
        this.currentPaperId = target.id;
        this.currentPaperDept = target.deptId;
        this.$http({
          url: this.$http.adornUrl('/kpi/item/listItem'),
          method: 'post',
          data: this.$http.adornParams({
            'deptId': this.currentPaperDept,
            'withPublic': true,
            'page': 1,
            'limit': 2000
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            data.data.list.forEach((item) => {
              this.itemPidArr[item.pid].push(item);
            })
          }else {
            this.$message.error(data.msg)
          }
        })
        this.getPaperDetail(target)
      },
      getPaperDetail(target, delId = false) {
        this.$http({
          url: this.$http.adornUrl('/kpi/paper/withDetailById'),
          method: 'post',
          params: this.$http.adornParams({
            'paperId': target.id,
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            if(data.data.items.length === 0){
              this.createNewPaper()
            }else {
              data.data.items.forEach((item) => {
                if(delId) item.id = ''
                item.scoresGiverIds = [];
                item.scoresGiverNames = []
                item.scoresGivers.forEach((user) => {
                  item.scoresGiverIds.push(user.scoresGiverId)
                  item.scoresGiverNames.push(user.scoresGiverName)
                })
              })
              this.paperData = data.data.items;
              if(this.paperData.findIndex(x=>x.kpiItemPid === '3')<0){
                this.paperData.push(this.deepCopy(this.itemTemplate['3']),this.deepCopy(this.itemTemplate['3']));
              }
              this.computedColLine(this.paperData);
              this.addClassIndex = this.OrderIndexArr.map((item,idx) => (item + this.OrderIndexLenth[idx] -1))
            }
          }else {
            this.$message.error(data.msg)
          }
        }).finally(() => {
          this.searchLoading = false;
          this.kpiPaperDialog = true;
        })
      },
      createNewPaper() {
        let newPaper = [];
        newPaper.push(this.deepCopy(this.itemTemplate['1']),this.deepCopy(this.itemTemplate['1']),this.deepCopy(this.itemTemplate['1']));
        newPaper.push(this.deepCopy(this.itemTemplate['2']),this.deepCopy(this.itemTemplate['2']),this.deepCopy(this.itemTemplate['2']));
        newPaper.push(this.deepCopy(this.itemTemplate['3']),this.deepCopy(this.itemTemplate['3']));
        newPaper.push(this.deepCopy(this.itemTemplate['4']),this.deepCopy(this.itemTemplate['4']),this.deepCopy(this.itemTemplate['4']),this.deepCopy(this.itemTemplate['4']));
        this.paperData = newPaper;
        this.computedColLine(this.paperData);
        this.addClassIndex = this.OrderIndexArr.map((item,idx) => (item + this.OrderIndexLenth[idx] -1))
        this.kpiPaperDialog = true;
      },
      removeItem(scope) {
        let type = parseInt(scope.row.kpiItemPid) - 1;
        let idx = scope.$index;
        this.OrderIndexArr.forEach((item,idx) => {
          if(idx > type) this.OrderIndexArr[idx]--
        })
        this.OrderIndexLenth[type]--;
        this.addClassIndex = this.OrderIndexArr.map((item,idx) => (item + this.OrderIndexLenth[idx] -1))
        this.paperData.splice(idx,1)
      },
      addItem(scope) {
        let type = parseInt(scope.row.kpiItemPid) - 1;
        let idx = scope.$index;
        this.OrderIndexArr.forEach((item,idx) => {
          if(idx > type) this.OrderIndexArr[idx]++
        })
        this.OrderIndexLenth[type]++;
        this.addClassIndex = this.OrderIndexArr.map((item,idx) => (item + this.OrderIndexLenth[idx] -1))
        this.paperData.splice(idx+1, 0, this.deepCopy(this.itemTemplate[scope.row.kpiItemPid]))
      },
      deepCopy (obj, cache = []) {
        if (obj === null || typeof obj !== 'object') {
          return obj
        }
        const hit = cache.filter(c => c.original === obj)[0]
        if (hit) {
          return hit.copy
        }
        const copy = Array.isArray(obj) ?  [] :   {}
        cache.push({
          original: obj,
          copy
        })
        Object.keys(obj).forEach(key => {
          copy[key] = this.deepCopy(obj[key], cache)
        })

        return copy
      },
      savePaper() {
        let postData = [];
        let notice = [];
        this.paperData.forEach((item, idx) => {
          if(item.kpiItemId) {
            if(item.scoresGiverIds.length > 0) {
              item.paperId = this.currentPaperId
              postData.push(item)
            }else {
              notice.push(idx + 1);
            }
          }
        })

        if(notice.length > 0) return this.$message.error(`第${notice.join(',')}题还未设置评分人`)

        this.$http({
          url: this.$http.adornUrl('/kpi/paper/savePaper'),
          method: 'post',
          data: postData
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.kpiPaperDialog = false;
            this.$notify({
              title: '成功',
              message: '保存成功',
              type: 'success'
            });
            this.searchList();
          }else {
            this.$message.error(data.msg)
          }
        }).finally(() => {

        })
      },
      notifyAction() {
        this.$confirm('您确定要通知未评分人进行评分吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.notifyLoading = true;
          this.$http({
            url: this.$http.adornUrl('/kpi/paper/sendTaskNotice'),
            method: 'post'
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$notify({
                title: '成功',
                message: '通知成功',
                type: 'success'
              });
            }else {
              this.$message.error(data.msg)
            }
          }).finally(() => {
            this.notifyLoading = false;
          })
        })
      },
      reAssess() {
        this.$http({
          url: this.$http.adornUrl('/kpi/paper/editScores'),
          method: 'post',
          params: this.$http.adornParams(this.scoreForm)
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.$notify({
              title: '成功',
              message: '打分成功',
              type: 'success'
            });
            this.openCheckDialog(this.currentPaperId)
          }else {
            this.$message.error(data.msg)
          }
        }).finally(() => {
          this.reAssessDialog = false;
        })
      },
      openReAssessDialog(kpiItem) {
        this.reAssessDialog = true;
        this.scoreForm.scores = 0;
        this.scoreForm.remark = '';
        this.scoreForm.paperDetailId = kpiItem.id;
      },
      exportExcel() {
        this.$http({
          url: this.$http.adornUrl('/kpi/paper/exportKpiExcel'),
          method: 'get',
          params: this.$http.adornParams({
            kpiDate: this.searchMonth
          }),
          responseType: 'blob'
        }).then((res) => {
          this.downFile(res.data, `${this.searchMonth.replace('-','')}绩效考核.xls`);
        }).finally(() => {
          this.reAssessDialog = false;
        })
      },
      exportDetail(){
        this.$http({
          url: this.$http.adornUrl('/kpi/paper/exportKpiDetailExcel'),
          method: 'get',
          params: this.$http.adornParams({
            kpiDate: this.searchMonth
          }),
          responseType: 'blob'
        }).then((res) => {
          this.downFile(res.data, `${this.searchMonth.replace('-','')}绩效考核明细.xls`);
        }).finally(() => {
          this.reAssessDialog = false;
        })
      },
      downFile(blob, fileName) {
        if (window.navigator.msSaveOrOpenBlob) {
          navigator.msSaveBlob(blob, fileName);
        } else {
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = fileName;
          link.click();
          window.URL.revokeObjectURL(link.href);
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .assessed-info{
    display:inline-block;
    color:#606266;
    p{
      display:inline-block;
      margin-right:25px;
      font-weight: bold;
      span{
        display: inline-block;
        font-weight: normal;
        width: 130px;
        text-align: center;
        border-bottom: 1px solid #606266;
      }
    }
  }
  .notice{
    margin-top:10px;
    color:red;
    padding-left:120px;
  }
  .list-wrapper-class .el-select.el-select--medium{
    width: 90%;
  }
</style>
